﻿// =================================================================== 
// 项目说明
//====================================================================
// lsc @Copy Right 2019
// 文件： ProductRepository.cs
// 项目名称：斑马车务
// 创建时间：2019-07-31
// 负责人：lsc
// ===================================================================
using System;
using System.Text;
using System.Collections.Generic;
using YouWei.Infrastructure.Entity;
using Dapper;
using Dapper.Extensions;
using YouWei.Infrastructure.Models;

namespace YouWei.Infrastructure.Repository
{
	/// <summary>
	///产品 仓储层
	/// </summary>	
	public class ProductRepository:BaseRepository<Product>
	{		
    
        #region 构造

        public ProductRepository() : base(){}

        public ProductRepository(string connectionString) : base(connectionString){}

        public ProductRepository(DatabaseContext dbContext) : base(dbContext){}


        #endregion
        /// <summary>
        /// 查询产品列表
        /// 此方法仅用于管理员
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public Page<Product> Pages(int pageIndex, int pageSize, ProductSearchModel model)
        {
            StringBuilder sb = new StringBuilder("SELECT * FROM [Product] T1 WITH(NOLOCK) WHERE T1.IsActive=1");
            var dparams = new DynamicParameters();
            if (model != null)
            {
                AddParams(model, sb, dparams);
            }

            sb.Append(" ORDER BY T1.UpdateDate DESC");
            return Pages(pageIndex, pageSize, sb.ToString(), dparams);
        }
        /// <summary>
        /// 构建查询条件
        /// </summary>
        /// <param name="model"></param>
        /// <param name="sb"></param>
        /// <param name="dparams"></param>
        private void AddParams(ProductSearchModel model, StringBuilder sb, DynamicParameters dparams)
        {
            if (model.UserID>0)
            {
                sb.Append(" AND T1.UserID=@UserID");
                dparams.Add("UserID", model.UserID, System.Data.DbType.Int32);
            }

            if (!string.IsNullOrWhiteSpace(model.OpenID))
            {
                sb.Append(" AND T1.OpenID=@OpenID");
                dparams.Add("OpenID", model.OpenID, System.Data.DbType.String);
            }
            else if (model.ProductID > 0)
            {
                sb.Append(" AND T1.ProductID=@ProductID");
                dparams.Add("ProductID", model.ProductID, System.Data.DbType.Int32);
            }

            if (!string.IsNullOrEmpty(model.ProductName))
            {
                sb.Append(" AND charindex(@ProductName,T1.ProductName)>0");
                dparams.Add("ProductName", model.ProductName, System.Data.DbType.String);
            }
           
        }
    }
}